package com.warom.sdg.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.PlcDataEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 原生SQLite实现的PLC数据DAO
 */
public class PlcDataDao_Impl implements PlcDataDao {
    private static final String TAG = "PlcDataDao_Impl";

    private final SdgDatabase database;

    public PlcDataDao_Impl(SdgDatabase database) {
        this.database = database;
    }

    @Override
    public long insert(PlcDataEntity data) {
        SQLiteDatabase db = database.getWritableDatabase();
        long id = -1;

        try {
            ContentValues values = new ContentValues();
            values.put(SdgDatabase.COLUMN_DEVICE_ID, data.getDeviceId());
            values.put(SdgDatabase.COLUMN_NAME, data.getName());
            values.put(SdgDatabase.COLUMN_ADDRESS, data.getAddress());
            values.put(SdgDatabase.COLUMN_TYPE, data.getType());
            values.put(SdgDatabase.COLUMN_VALUE, data.getValue());
            values.put(SdgDatabase.COLUMN_UNIT, data.getUnit());
            values.put(SdgDatabase.COLUMN_TIMESTAMP, data.getTimestamp());
            values.put(SdgDatabase.COLUMN_TIME_STRING, data.getTimeString());

            id = db.insert(SdgDatabase.TABLE_PLC_DATA, null, values);
            Log.d(TAG, "已插入PLC数据记录，ID: " + id);
        } catch (Exception e) {
            Log.e(TAG, "插入PLC数据失败: " + e.getMessage(), e);
        }

        return id;
    }

    @Override
    public List<PlcDataEntity> getAllData() {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    null,
                    null,
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取全部数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public List<PlcDataEntity> getDataByDeviceId(int deviceId) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_DEVICE_ID + " = ?",
                    new String[] { String.valueOf(deviceId) },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按设备ID获取数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public List<PlcDataEntity> getDataByName(String name) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_NAME + " = ?",
                    new String[] { name },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按名称获取数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public List<PlcDataEntity> getDataByAddress(String address) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_ADDRESS + " = ?",
                    new String[] { address },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按地址获取数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public List<PlcDataEntity> getDataByDeviceAndAddress(int deviceId, String address) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_DEVICE_ID + " = ? AND " + SdgDatabase.COLUMN_ADDRESS + " = ?",
                    new String[] { String.valueOf(deviceId), address },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按设备ID和地址获取数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public List<PlcDataEntity> getDataByType(String type) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_TYPE + " = ?",
                    new String[] { type },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC");

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按类型获取数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public PlcDataEntity getLatestDataByAddress(String address) {
        SQLiteDatabase db = database.getReadableDatabase();
        PlcDataEntity entity = null;

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_ADDRESS + " = ?",
                    new String[] { address },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC",
                    "1");

            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取最新数据失败: " + e.getMessage(), e);
        }

        return entity;
    }

    @Override
    public PlcDataEntity getLatestDataByDeviceAndAddress(int deviceId, String address) {
        SQLiteDatabase db = database.getReadableDatabase();
        PlcDataEntity entity = null;

        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    SdgDatabase.COLUMN_DEVICE_ID + " = ? AND " + SdgDatabase.COLUMN_ADDRESS + " = ?",
                    new String[] { String.valueOf(deviceId), address },
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC",
                    "1");

            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取设备最新数据失败: " + e.getMessage(), e);
        }

        return entity;
    }

    @Override
    public void deleteAll() {
        SQLiteDatabase db = database.getWritableDatabase();
        try {
            int count = db.delete(SdgDatabase.TABLE_PLC_DATA, null, null);
            Log.d(TAG, "已删除所有PLC数据 (" + count + " 条)");
        } catch (Exception e) {
            Log.e(TAG, "删除所有数据失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void deleteDataBefore(long timestamp) {
        SQLiteDatabase db = database.getWritableDatabase();
        try {
            int count = db.delete(
                    SdgDatabase.TABLE_PLC_DATA,
                    SdgDatabase.COLUMN_TIMESTAMP + " < ?",
                    new String[] { String.valueOf(timestamp) });

            Log.d(TAG, "已删除 " + count + " 条旧数据");
        } catch (Exception e) {
            Log.e(TAG, "删除旧数据失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void deleteDataByDeviceId(int deviceId) {
        SQLiteDatabase db = database.getWritableDatabase();

        try {
            int rowsDeleted = db.delete(
                    SdgDatabase.TABLE_PLC_DATA,
                    SdgDatabase.COLUMN_DEVICE_ID + " = ?",
                    new String[] { String.valueOf(deviceId) });

            Log.d(TAG, "删除设备ID " + deviceId + " 的数据完成，共删除 " + rowsDeleted + " 条记录");
        } catch (Exception e) {
            Log.e(TAG, "删除设备数据失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<PlcDataEntity> getHistoryData(int deviceId, String address, long startTime, long endTime, int limit) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDataEntity> dataList = new ArrayList<>();

        try {
            // 构建查询条件
            String selection = SdgDatabase.COLUMN_DEVICE_ID + " = ? AND "
                    + SdgDatabase.COLUMN_ADDRESS + " = ? AND "
                    + SdgDatabase.COLUMN_TIMESTAMP + " >= ? AND "
                    + SdgDatabase.COLUMN_TIMESTAMP + " <= ?";

            String[] selectionArgs = new String[] {
                    String.valueOf(deviceId),
                    address,
                    String.valueOf(startTime),
                    String.valueOf(endTime)
            };

            // 执行查询，并按时间戳降序排序
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DATA,
                    null,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    SdgDatabase.COLUMN_TIMESTAMP + " DESC",
                    String.valueOf(limit));

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    dataList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }

            Log.d(TAG, "获取历史数据: 设备ID=" + deviceId + ", 地址=" + address
                    + ", 时间范围=" + startTime + "-" + endTime
                    + ", 获取到 " + dataList.size() + " 条记录");
        } catch (Exception e) {
            Log.e(TAG, "获取历史数据失败: " + e.getMessage(), e);
        }

        return dataList;
    }

    /**
     * 将查询结果转换为实体对象
     */
    private PlcDataEntity cursorToEntity(Cursor cursor) {
        PlcDataEntity entity = new PlcDataEntity();

        int idIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_ID);
        if (idIndex != -1) {
            entity.setId(cursor.getInt(idIndex));
        }

        int deviceIdIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DEVICE_ID);
        if (deviceIdIndex != -1) {
            entity.setDeviceId(cursor.getInt(deviceIdIndex));
        }

        int nameIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_NAME);
        if (nameIndex != -1) {
            entity.setName(cursor.getString(nameIndex));
        }

        int addressIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_ADDRESS);
        if (addressIndex != -1) {
            entity.setAddress(cursor.getString(addressIndex));
        }

        int typeIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_TYPE);
        if (typeIndex != -1) {
            entity.setType(cursor.getString(typeIndex));
        }

        int valueIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_VALUE);
        if (valueIndex != -1) {
            entity.setValue(cursor.getString(valueIndex));
        }

        int unitIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_UNIT);
        if (unitIndex != -1) {
            entity.setUnit(cursor.getString(unitIndex));
        }

        int timestampIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_TIMESTAMP);
        if (timestampIndex != -1) {
            entity.setTimestamp(cursor.getLong(timestampIndex));
        }

        int timeStringIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_TIME_STRING);
        if (timeStringIndex != -1) {
            entity.setTimeString(cursor.getString(timeStringIndex));
        }

        return entity;
    }
}